package com.lenovo.server.weixin;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.lf5.LogLevel;

import com.lenovo.server.weixin.util.SignUtil;

public class DealWeixinRequest extends HttpServlet{
	static Logger  mLog = Logger.getLogger("DealWeixinRequest");
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		slog.p("do get>>");
		
		Log log = LogFactory.getLog(getClass());
		log.debug("doGet");
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		slog.p(
				"signature " +signature +
				" timestamp " + timestamp + 
				" nonce " + nonce + 
				" echostr " + echostr
				);
		PrintWriter out = response.getWriter();
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
			out.flush();
			return;
		}
		
		
		doPost(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		slog.p("doPost>>>");
		slog.p("doPost>>>");
		request.setCharacterEncoding("UTF-8"); 
		response.setCharacterEncoding("UTF-8"); 
//		response.setContentType("text/html;charset=gb2312");
		
//		PrintWriter writer = resp.getWriter();
//		writer.print(echostr);
//		writer.flush();
		
		
		String respMessage = CoreService.processRequest(request); 
		
		if(respMessage == null){
			respMessage = "解析有错误" ;
		}
		
		PrintWriter output = response.getWriter(); 
		try {
			slog.p("print message  to weixin server now " +respMessage);
		} catch (Exception e) {
		}
		slog.p("send msg to weixinserver " + respMessage);
//		OutputStream output = response.getOutputStream();
		System.out.println("message is " + respMessage);
//		output.write(respMessage.getBytes("utf-8"));
		output.print(respMessage);
		output.flush();
		
	}
}
